<%@page import="java.util.UUID"%>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@ include file="/WEB-INF/pages/common/taglib.jsp" %>
<%
    String uuid = UUID.randomUUID().toString();
    request.setAttribute("uuid", uuid);
%>
<div class="row">
    <div class="col-md-3">
    	<div class="box box-primary">
    		<div class="box-header with-border">
    			<h3 class="box-title">
    			
    			</h3>
    			<div class="box-tools pull-right" id="orgToolForm_${uuid}">
    				<shiro:hasPermission name="ORG_MGR_ADD">
			    	<a href="javascript:void(0)" class="btn btn-sm btn-success addBt ">
			            <span class="glyphicon glyphicon-plus" aria-hidden="true"></span> 添加
			        </a>
			        </shiro:hasPermission>
			        
			        <shiro:hasPermission name="ORG_MGR_MOD">
			        <a href="javascript:void(0)" class="btn btn-sm btn-primary editBt ">
			            <span class="glyphicon glyphicon-edit" aria-hidden="true"></span> 修改
			        </a>
			        </shiro:hasPermission>
			        
			        <shiro:hasPermission name="ORG_MGR_DEL">
			        <a href="javascript:void(0)" class="btn btn-sm btn-danger delBt ">
			            <span class="glyphicon glyphicon-trash" aria-hidden="true"></span> 删除
			        </a>
			        </shiro:hasPermission>
    			</div>
    		</div>
    		<div class="box-body">
	    		<div id="orgTree_${uuid}" class="ztree">
	        	</div>
	    	</div>
    	</div>
    </div>
    <div class="col-md-9">
    	<div class="nav-tabs-custom">
    				<ul class="nav nav-tabs" role="tablist">
			    		<li class="active">
			    			<a href="#userMgrTab_${uuid }" role="tab" data-toggle="tab">
			    			<span class="glyphicon glyphicon-exclamation-sign" aria-hidden="true"></span> 用户管理
			    			</a>
			    		</li>
			    		<li>
			    			<a href="#orgConfigTab_${uuid }" role="tab" data-toggle="tab">
			    			<span class="glyphicon glyphicon-paperclip" aria-hidden="true"></span> 单位关系配置
			    			</a>
			    		</li>
			    	</ul>
			    	<div class="tab-content">
			    		<div role="tabpanel" class="tab-pane active" id="userMgrTab_${uuid}">
			    			
					    		<div class="box-header with-border">
					    			<h3 class="box-title">
					    			
					    			</h3>
					    			<div class="box-tools pull-right" id="userMgrGridTB_${uuid}">
					    				<div class="btn-group">
							    			<shiro:hasPermission name="USER_MGR_ADD">
								    		<button class="btn btn-sm btn-success addBtn">
								    			<span class="glyphicon glyphicon-plus" aria-hidden="true"></span> 添加
								    		</button>
								    		</shiro:hasPermission>
								    		
								    		<shiro:hasPermission name="USER_MGR_MOD">
								    		<button class="btn btn-sm btn-primary editBtn">
								    			<span class="glyphicon glyphicon-pencil" aria-hidden="true"></span> 修改
								    		</button>
								    		</shiro:hasPermission>
								    		
								    		<shiro:hasPermission name="USER_MGR_DEL">
								    		<button class="btn btn-sm btn-danger delBtn">
								    			<span class="glyphicon glyphicon-trash" aria-hidden="true"></span> 删除
								    		</button>
								    		</shiro:hasPermission>
							    		</div>
							    		
							    		<shiro:hasPermission name="USER_ORG_REL_DEL">
							    		<button class="btn btn-sm btn-danger removeFromOrgBtn">
							    			<span class="glyphicon glyphicon-trash" aria-hidden="true"></span> 从组织机构中移出
							    		</button>
							    		</shiro:hasPermission>
					    			</div>
					    		</div>
					    		<div class="box-body">
						    		<table id="userMgrGrid_${uuid}"></table>
						    	</div>
			    		</div>
			    		<div role="tabpanel" class="tab-pane" id="orgConfigTab_${uuid}">
			    			<div class="box-body">
				    			<div id="orgRel_${uuid}" class="row" style="display: none;">
									<pf:dataDic dicCode="ORG_REL_TYPE" var="item">
										<div class="col-md-4">
										<div class="panel am-margin-sm org-rel-type-item panel-primary" style="width:98%">
											  <div class="panel-heading">${item.name}</div>
											  
										      <ul class="list-group org-rel-type-item-content" id="${item.code}_relItems">
												       	
											  </ul>
											  <div class="panel-footer">
											  	  <shiro:hasPermission name="ORG_ATTR_MOD">
												  <a href="javascript:void(0)" data-code="${item.code}" data-value="${item.value}" class="btn  btn-sm  btn-default orgRelEditBt">
											         <span class="glyphicon glyphicon-edit" aria-hidden="true"></span> 配置
											      </a>
											      </shiro:hasPermission>
										      </div>
										</div>
										</div>
									</pf:dataDic>
								</div>
				    		</div>
			    		</div>
			    	</div>
    			</div>
    
    
    	
    </div>
</div>

<script type="text/javascript">
    $(function () {
        var uuid = '${uuid}';

        var orgTree = $("#orgTree_"+uuid);
        var userGrid = $("#userMgrGrid_"+uuid);
        var userMgrGridTB=$("#userMgrGridTB_"+uuid);
        var orgToolForm = $("#orgToolForm_"+uuid);
        
        var editOrg=function(params){
            params = params || {};
            var t = [];
            if (params.id) {
                t.push("id=" + params.id);
            }
            if (params.pid) {
                t.push("pid=" + params.pid);
            }
            
            var dialog=webUtils.dialog({
              	 title:'编辑组织机构',
              	 url:ctx + '/orgAction/editView.do?' + t.join("&"),
              	 onremove:function () {
                       if (params.onClose) {
                           params.onClose.call(null);
                       }
                   }
               });
            return dialog;
        }
        
        orgToolForm.find(".addBt").click(function () {
            var nodes = orgTree.getSelectedNodes();
            if (nodes && nodes.length > 0) {
                var node = nodes[0];
                var sub = top.webUtils.topicSubscribe("org.edit.success", function (args) {
                    var cnode = args.obj;
                    orgTree.addNodes(node, cnode);
                    dialog.close();
                },true);
                var dialog = editOrg({
                    pid: node.id,
                    onClose: function () {
                        sub.remove();
                    }
                });
            } else {
                webUtils.alert("请选择其中一个");
            }
        });

        orgToolForm.find(".editBt").click(function () {
            var nodes = orgTree.getSelectedNodes();
            if (nodes && nodes.length > 0) {
                var node = nodes[0];
                var sub = top.webUtils.topicSubscribe("org.edit.success", function (args) {
                    var cnode = args.obj;
                    orgTree.updateNode($.extend(node, cnode));
                    dialog.close();
                });
                var dialog = editOrg({
                    id:node.id,
                    onClose: function () {
                        sub.remove();
                    }
                },true);
            } else {
                webUtils.alert("请选择其中一个");
            }
        });

        orgToolForm.find(".delBt").click(function () {
            var nodes = orgTree.getSelectedNodes();
            if (nodes && nodes.length > 0) {
            	webUtils.confirm("删除后将不可恢复，请问是否继续?", function(result) {
					if(result){
						var ids = [];
		                $.each(nodes, function (i, n) {
		                    ids.push(n.id);
		                });
		                $.post(ctx + "/orgAction/delOrg.do", {ids: ids.join(",")}, function (data) {
		                    if (data.success) {
		                        $.each(nodes, function (i, n) {
		                            orgTree.removeNode(n);
		                        });
		                    } else {
		                        webUtils.error(data.msg);
		                    }
		                }, 'json');
					}
        		});
            } else {
                alert("请勾选至少个");
            }
        });
        
        orgTree = $.fn.zTree.init(orgTree, {
            treeId: "orgTree",
            async: {
                enable: true,
                url: ctx + "/orgAction/queryOrgTreeNodes.do",
                autoParam: ["id=pid"],
                dataFilter: function (treeId, parentNode, responseData) {
                    if (responseData) {
                        $.each(responseData, function (i, n) {
                            if (n.childrenSize > 0) {
                                n.isParent = true;
                            }
                        });
                    }
                    return responseData;
                }
            },
            data: {
                key: {
                    name: "text"
                }
            },
            edit: {
            },
            callback: {
                onClick: function (e, treeId, treeNode, clickFlag) {
                    if (clickFlag != 0) {
                        userGrid.orgId = treeNode.id
                        userGrid.bootstrapTable("refresh");
                        
                        if(treeNode.id!=-1){
                			$("#orgRel_"+uuid).show();
                			refreshOrgRelExtAttrs(treeNode.id);
                		}else{
                			$("#orgRel_"+uuid).hide();
                		}
                    }
                }
            }
        }, [{
                text: "组织机构",
                id: "-1",
                isParent: true,
                open: true
            }]);
        orgTree.reAsyncChildNodes(orgTree.getNodesByParam("id", "-1")[0], "refresh");

        
        $(".orgRelEditBt").click(function(){
        	var selectedRows=orgTree.getSelectedNodes();
        	var orgId=selectedRows[0].id;
        	var code=$(this).data("code");
        	var value=eval('('+$(this).data("value")+')');
        	if(value.type==1){
        		webUtils.orgSelector({
        			isSingle:value.single,
            		onSelect:function(rows){
            			var rels=[];
            			$.each(rows,function(i,n){
            				rels.push({
            					orgId:orgId,
            					extCode:code,
            					attrVal:n.id,
            					attrViewName:n.name,
            					attrType:value.type
            				})
            			});
            			addRel(code,rels,true,value.single);
            		} 
            	});
        	}else if(value.type==2){
        		webUtils.userSelector({
        			isSingle:value.single,
            		onSelect:function(rows){
            			var rels=[];
            			$.each(rows,function(i,n){
            				rels.push({
            					orgId:orgId,
            					extCode:code,
            					attrVal:n.id,
            					attrViewName:n.userName,
            					attrType:value.type
            				})
            			});
            			addRel(code,rels,true,value.single);
            		} 
            	});
        	}
        });
        
        function addRel(code,rels,saveToServer,isSingle){
        	var  relBox=$("#"+code+"_relItems");
        	if(isSingle){
        		relBox.find(".org-rel-type-item-val").each(function(i,n){
        			delOrgRelExtAttr($(n));
        		});
        	}
        	
        	$.each(rels,function(i,n){
        		if(relBox.find("li[val='"+n.attrVal+"']").size()<=0){
        			var isSaveSuccess=false;
            		if(saveToServer){
            			$.ajax({
            				async:false,
            				data:n,
            				dataType:"json",
            				type:"POST",
            				url:ctx+"/orgAction/saveOrgExtAttr.do",
            				success:function(data){
            					if(data.success){
            						isSaveSuccess=true;
            						n=data.obj;
            					}
            					
            				}
            			});
            		}else{
            			isSaveSuccess=true;
            		}
            		if(isSaveSuccess){
            			var html="<li class='list-group-item org-rel-type-item-val' val='"+n.attrVal+"'>"
           				+n.attrViewName
           	       		+'<button type="button" class="close delBtn" aria-label="Close"><span aria-hidden="true">&times;</span></button>'
           	       		+'</li>';
           	       		var dom=$(html);
           	       		dom.data("data",n);
           				relBox.append(dom);
            		}
        		}
        	});
        }
        
        function refreshOrgRelExtAttrs(orgId){
        	$(".org-rel-type-item .org-rel-type-item-content").each(function(){
        		$(this).html("");
        	});
        	
        	$.getJSON(ctx+"/orgAction/loadOrgExtAttrs.do",{orgId:orgId},function(datas){
        		$.each(datas,function(i,n){
        			addRel(n.extCode,[n]);
        		})
        	});
        }
        
        $("#orgRel_"+uuid).delegate(".delBtn","click",function(){
        	var liDom=$(this).parent("li");
        	delOrgRelExtAttr(liDom);
        });
        
        function delOrgRelExtAttr(liDom){
        	var data=liDom.data("data");
        	$.ajax({
				async:false,
				data:{ids:data.id},
				dataType:"json",
				type:"POST",
				url:ctx+"/orgAction/delOrgExtAttrs.do",
				success:function(r){
					if(r.success){
	        			liDom.remove();
	        		}else{
	        			webUtils.error(r.msg);
	        		}
				}
			});
        }
        
        userGrid = userGrid.bootstrapTable({
        	url:ctx + "/userAction/queryByOrgId.do",
        	queryParams:function(d){
        		if(userGrid && userGrid.orgId){
	    			d.orgId=userGrid.orgId;
	    		}
				return d;
        	},
            columns: [
					{field: '_id',checkbox:true},
                    {title: '登录名称', field: 'loginName',align: 'left', width: 80},
                    {title: '用户名', field: 'userName', align: 'left', width: 80},
                    {title: '手机号', field: 'mobileNo', align: 'left', width: 120},
                    {title: '证件号', field: 'idCardNo', align: 'left', width: 140},
                    {title: '是否失效', field: 'enabled', align: 'left', width: 80, formatter:function(value,row, index) {
                            if (value == 1) {
                                return "";
                            } else {
                                return "是";
                            }
                        }},
                    {title: '解锁', field: 'locked', align: 'left', width: 80, formatter:function(value,row, index) {
                    	return "<a href='javascript:void(0)' class='unlocked' data-id='"+row.id+"'>解除</a>";
                   }}
                ],
            onLoadSuccess: function () {
            	userGrid.find(".unlocked").click(function(){
            		var id=$(this).data("id");
            		var datas={
            				id:id
            		}
            		$.post(ctx+"/userAction/unlock.do",{datas:Base64.encode(JSON.stringify(datas))},function(data){
            			if(data.success){
            				webUtils.alert("解锁成功!");
            			}else{
            				webUtils.alert("解锁失败！");
            			}
            		},"json")
            	});
            }
        });
        
        userMgrGridTB.find(".addBtn").click(function(){
        	var nodes = orgTree.getSelectedNodes();
            if (nodes && nodes.length > 0) {
            	var node = nodes[0];
            	var sub=top.webUtils.topicSubscribe("user.edit.success", function (args) {
                    userGrid.bootstrapTable("refresh");
                    dialog.close();
                });
            	var dialog=editUserInfoPanelContent({
            		orgId:node.id,
            		onClose: function () {
                        sub.remove();
                    }
            	});
            } else {
                webUtils.alert("请选择所属组织机构");
            }
        });
        
        userMgrGridTB.find(".editBtn").click(function(){
        	var rows=userGrid.bootstrapTable("getSelections");
        	if(rows && rows.length>0){
        		var nodes = orgTree.getSelectedNodes();
                var orgId = "";
                if (nodes && nodes.length > 0) {
                    var node = nodes[0];
                    orgId = node.id;
                }
        		var sub = top.webUtils.topicSubscribe("user.edit.success", function (args) {
            		dialog.close();
            		userGrid.bootstrapTable("refresh");
                });
        		var row=rows[0];
        		var dialog=editUserInfoPanelContent({
        			id:row.id,
            		orgId:orgId,
            		onClose: function () {
                        sub.remove();
                    }
            	});
        	}else{
        		 webUtils.alert("请选择需要编辑的数据");
        	} 
        });
        
        userMgrGridTB.find(".delBtn").click(function(){
        	webUtils.confirm("删除后将不可恢复，请问是否继续?", function(result) {
        		if(result){
        			var rows=userGrid.bootstrapTable("getSelections");
                	if(rows && rows.length>0){
                		var selecteds = [];
                        $.each(rows, function (i, n) {
                            selecteds.push(n.id);
                        });
                        
                        var orgId = "";
                        var nodes = orgTree.getSelectedNodes();
                        if (nodes && nodes.length > 0) {
                            var node = nodes[0];
                            orgId = node.id;
                        }
                        
                        $.post(ctx + "/userAction/delUser.do", {
                            ids: selecteds.join(","),
                            orgId: orgId
                        }, function (data) {
                            if (data.success) {
                            	userGrid.bootstrapTable("refresh");
                            } else {
                            	webUtils.alert(data.msg);
                            }
                        }, 'json');
                	} else {
                		webUtils.alert("请选择需要删除的数据");
                    }
        		}
        	});
        	
        });
        
        userMgrGridTB.find(".removeFromOrgBtn").click(function(){
        	webUtils.confirm("删除后将不可恢复，请问是否继续?", function(result) {
        		if(result){
        			var rows=userGrid.bootstrapTable("getSelections");
                	if(rows && rows.length>0){
                		var selecteds = [];
                        $.each(rows, function (i, n) {
                            selecteds.push(n.id);
                        });
                        
                        var orgId = "";
                        var nodes = orgTree.getSelectedNodes();
                        if (nodes && nodes.length > 0) {
                            var node = nodes[0];
                            orgId = node.id;
                        }
                        
                        $.post(ctx + "/userAction/removeUserFromOrg.do", {
                            ids: selecteds.join(","),
                            orgId: orgId
                        }, function (data) {
                            if (data.success) {
                            	userGrid.bootstrapTable("refresh");
                            } else {
                            	webUtils.alert(data.msg);
                            }
                        }, 'json');
                	} else {
                		webUtils.alert("请选择需要移除的数据");
                    }
        		}
        	});

        });
        
        
        function editUserInfoPanelContent(params) {
        	params = params || {};
            var t = [];
            if (params.id) {
                t.push("id=" + params.id);
            }
            if (params.orgId) {
                t.push("orgId=" + params.orgId);
            }
            
            var dialog=webUtils.dialog({
           	 title:'编辑用户信息',
           	 url:ctx + '/userAction/editView.do?' + t.join("&"),
           	 onremove:function () {
                    if (params.onClose) {
                        params.onClose.call(null);
                    }
                }
            });
            return dialog;
        }
        
    });
</script>